﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using AirForceCDCTests.src.main;

namespace AirForceCDCTests
{
    /// <summary>
    /// Interaction logic for QuestionBank.xaml
    /// </summary>
    public partial class QuestionBank : Window
    {
        private List<Question> questions;
        private string selectedCDC = "";
        private int numOfQuestions = 0;
        private MainWindow mainWindow;
        private int selectedQuestions = 0;
        private Random rng = new Random();
        private int lineNumber = 0;
        private bool volume = false;
        private string begVol = "";
        private string endVol = "";

        /// <summary>
        /// Loads a window to select the question bank
        /// </summary>
        /// <param name="mainWindow">Reference to the main window to allow
        /// the program to start after the questions have been choosen</param>
        public QuestionBank(MainWindow mainWindow)
        {
            MainWindow.DebugWindow.AddMessage("Loading Questions...");
            InitializeComponent();
            GetTests();
            testLevelList.SelectedIndex = 0;
            numQuestions.Focus();

            questions = new List<Question>();
            this.mainWindow = mainWindow;
            comboBox.SelectedIndex = 0;
            volumeBox.SelectedIndex = 0;
        }


        private void GetTests()
        {
            string[] files = Directory.GetFiles(@"cdcs", "*.txt");

            foreach (string s in files)
            {
                int startIndex = s.IndexOf("\\") + 1;
                int endIndex = s.IndexOf(".txt");
                string test = s.Substring(startIndex, endIndex - startIndex);
                testLevelList.Items.Add(test);

            }
        }

        private void okBtn_Click(object sender, RoutedEventArgs e)
        {
            selectedCDC = (string)testLevelList.Items.GetItemAt(testLevelList.SelectedIndex);
            string value = numQuestions.Text.Trim().Equals("") ? "0" : numQuestions.Text.Trim();
            try
            {
                numOfQuestions = int.Parse(value);
            }
            catch (FormatException)
            {
                MainWindow.ErrorWindow.SetErrorMessage("Must enter numerical number");
                MainWindow.DebugWindow.AddMessage("Must enter numerical number");
                return;
            }
            selectedQuestions = comboBox.SelectedIndex;
            begVol = String.Format("[volume{0}]", volumeBox.SelectedIndex);
            endVol = String.Format("[endvolume{0}]", volumeBox.SelectedIndex);
            LoadCDCs();
        }

        private void numQuestions_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                okBtn_Click(sender, e);
        }

        private void LoadCDCs()
        {
            StreamReader reader = new StreamReader(@"cdcs\\" + selectedCDC + ".txt");

            string line = "";
            while ((line = reader.ReadLine()) != null)
            {
                lineNumber++;
                if (line.Trim() == "") continue;

                string[] items = line.Split(':');
                
                if (items.Length != 6 && items.Length != 2 && !items[0].StartsWith("["))
                {
                    MainWindow.DebugWindow.AddMessage("Line # " + lineNumber +
                        " does not have enough parameters to add as a question\n\tSkipping...\n");
                    continue;
                }

                if (volumeBox.SelectedIndex == 0)
                    volume = true;
                else if (items[0].Equals(begVol))
                        volume = true;
                else if (items[0].Equals(endVol))
                        volume = false;


                if (!volume) continue;

                switch (selectedQuestions)
                {
                    case 0:
                        LoadTest(items);
                        LoadReview(items);
                        continue;
                    case 1:
                        LoadTest(items);
                        continue;
                    case 2:
                        LoadReview(items);
                        continue;
                    default:
                        LoadTest(items);
                        LoadReview(items);
                        continue;
                }
            }
            MainWindow.DebugWindow.AddMessage("Done loading questions");
            this.Close();
            reader.Close();

            numOfQuestions = numOfQuestions == 0 ? questions.Count : numOfQuestions;
            mainWindow.StartQuestions(questions, numOfQuestions); 
        }

        private void LoadReview(string[] items)
        {
            string question = items[0] + "?";
            List<string> choices = new List<string>();
            int answer = 0;
            if(items.Length == 2)
            {
                string item = items[1];
                item.Trim();
                item = item.Substring(0, 1).ToUpper() + item.Substring(1, item.Length - 1);
                choices.Add(item);
                for(int i = 0; i < 3; i++) 
                    choices.Add("None.");

                answer = 1;
                Question currentQuestion = new Question(question.Trim(), choices, answer, rng.Next(int.MaxValue));
                questions.Add(currentQuestion); 
            }
        }

        private void LoadTest(string[] items)
        {
            string question = items[0] + "?";
            List<string> choices = new List<string>();
            int answer = 0;
            if (items.Length == 6)
            {
                for (int choicesIndex = 1; choicesIndex < 5; choicesIndex++)
                {

                    string item = items[choicesIndex];

                    item.Trim();
                    item = item.Substring(0, 1).ToUpper() + item.Substring(1, item.Length - 1);

                    choices.Add(item + ".");
                }
                try
                {
                    answer = int.Parse(items[5]);
                }
                catch (FormatException)
                {
                    MainWindow.DebugWindow.AddMessage("Error on Line " + lineNumber + ": answer is in the wrong format (must be numerical)");
                    return;
                }

                Question currentQuestion = new Question(question.Trim(), choices, answer, rng.Next(int.MaxValue));
                questions.Add(currentQuestion); 
            }
        }

        private void GetVolumes()
        {
            volumeBox.Items.Clear();
            volumeBox.SelectedIndex = 0;

            volumeBox.Items.Add("All Volumes");
            StreamReader reader = new StreamReader(@"cdcs\\" + selectedCDC + ".txt");

            string line = "";
            int volume = 0;
            while ((line = reader.ReadLine()) != null)
            {
                if (line.StartsWith("[volume"))
                {
                    volumeBox.Items.Add("Volume " + ++volume);
                }
            }
        }

        private void cnclBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
            mainWindow.Close();
        }

        private void testLevelList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedCDC = (string)testLevelList.Items.GetItemAt(testLevelList.SelectedIndex);
            MainWindow.DebugWindow.AddMessage("Selected Test: " + selectedCDC);
            GetVolumes();
        }
    }
}
